package com.zw.mes.module.assemble.service;

import com.zw.mes.common.JsonResult;
import com.zw.mes.entity.asse.QrParse;
import com.zw.mes.entity.sys.User;
import com.zw.mes.module.assemble.entity.AsseAssemblyRoute;
import com.zw.mes.module.assemble.entity.AsseAssemblySheet;
import com.zw.mes.module.assemble.entity.AsseTransCheck;
import com.zw.mes.module.assemble.entity.AsseTransSheet;
import com.zw.mes.module.assemble.mapper.ApplyMapper;
import com.zw.mes.module.assemble.model.ApplyModel;
import com.zw.mes.module.assemble.repository.AsseAssemblyRouteRepository;
import com.zw.mes.module.assemble.repository.AsseAssemblySheetRepository;
import com.zw.mes.module.assemble.repository.AsseTransCheckRepository;
import com.zw.mes.module.assemble.repository.AsseTransSheetRepository;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.module.transpositionManager.model.Select2Model;
import com.zw.mes.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 装配申请质检 业务
 * @Author: China.wsg
 * @Date: 2021/04/23 14:12
 */
@Service
@SuppressWarnings("all")
public class ApplyService {

    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private AsseAssemblySheetRepository assemblySheetRepository;
    @Autowired
    private AsseAssemblyRouteRepository assemblyRouteRepository;
    @Autowired
    private AsseTransSheetRepository transSheetRepository;
    @Autowired
    private AsseTransCheckRepository transCheckRepository;
    @Autowired
    private LogService logService;

    /**
     * 查询待装配申请质检列表
     *
     * @param barCode 派工单二维码 规则：生产令号|图号|部分ID|2
     * @return
     */
    public List<ApplyModel> findAppListByBarCode(String barCode) {
        if (barCode == null || barCode.equals("")) {
            barCode = "1|1|1|2";// 页面打开时避免，空指针崩溃特殊处理
        }
        QrParse parse = getQrParse(barCode);
        if (parse == null) return null;
        return applyMapper.findAppListByBarCode(parse);
    }

    /**
     * 字符串截取
     *
     * @param code
     * @return
     */
    private QrParse getQrParse(String code) {
        String[] arr = code.split("\\|");
        if (arr == null || arr.length < 4) {
            return null;
        }
        QrParse parse = new QrParse();
        parse.setProNo(arr[0]);
        parse.setDrawNo(arr[1]);
        parse.setPartId(arr[2]);
        parse.setCategory(arr[3]);
        return parse;
    }

    /**
     * 获取最新可用数量
     *
     * @param id
     * @return
     */
    public Integer getNewMayApplyNum(Integer id) {
        return applyMapper.getNewMayApplyNum(id);
    }

    /**
     * 申请质检
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult apply(AsseAssemblyRoute route) {
        JsonResult jsonResult = new JsonResult();
        // 修改路线表数量 可申请数减少， 已申请数增加
        int num = applyMapper.updateRouteApply(route);
        AsseAssemblyRoute flowRoute = assemblyRouteRepository.getOne(route.getId());
        if (num == 0) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("申请失败，因申请数量超过可申请数量,可申请数量为" + flowRoute.getMayApplyNum() + "个零件！");
        } else {
            // 工序未开始转为执行中
            if (flowRoute.getStatus().compareTo(1) == 0){
                flowRoute.setStatus(2);
                assemblyRouteRepository.save(flowRoute);
            }
            // 生成转序单(装配转序单表)
            AsseTransSheet trans = new AsseTransSheet();
            trans.setRouteId(route.getId());
            trans.setNum(route.getApplyNum());
            User u = ShiroUtils.getUser();
            trans.setApplyCode(u.getAccount());
            trans.setApplyName(u.getName());
            trans.setApplyTime(new Date());
            trans.setApplyDept(u.getBranchName());
            transSheetRepository.save(trans);
            //生成装配质检表
            AsseTransCheck transCheck = new AsseTransCheck();
            transCheck.setTransId(trans.getId());
            transCheck.setStatus(1);
            transCheckRepository.save(transCheck);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("申请成功！");

            AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(flowRoute.getSheetId());
            logService.saveLog("派工单-申请质检", "转序单ID：" + trans.getId() + "，生产令号：" + assemblySheet.getProdNo()
                    + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                    + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName() + "<br>工序：" + flowRoute.getRoute()
                    + "<br>申请数量：" + trans.getNum());
        }
        return jsonResult;
    }

    /**
     * 派工单-历史申请列表
     *
     * @param applyModel
     * @return
     */
    public List<ApplyModel> findHistoryApplyListByQuery(ApplyModel applyModel) {
        applyModel.setApplyCode(ShiroUtils.getUser().getAccount());
        return applyMapper.findHistoryApplyListByQuery(applyModel);
    }

    /**
     * 撤销质检申请
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelApply(Integer id) {
        AsseTransSheet trans = transSheetRepository.getOne(id);
        // 转序单已被删除
        if (trans.getIsDel() == 1) {
            return 0;
        }
        // 如果已经被质检
        AsseTransCheck check = transCheckRepository.findByTransId(trans.getId());
        if (check.getStatus() != 1 && check.getStatus() != 4) {
            return 0;
        }
        applyMapper.updateTransIsdel(id, 1);
        AsseAssemblyRoute route = assemblyRouteRepository.getOne(trans.getRouteId());
        route.setApplyNum(trans.getNum());

        AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(route.getSheetId());
        logService.saveLog("派工单-撤销质检申请", "转序单ID：" + trans.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName() + "<br>工序：" + route.getRoute()
                + "<br>申请数量：" + trans.getNum());
        applyMapper.updateRouteDel(route);
        // 如果没申请质检，转序状态设置成未开始
        return applyMapper.updateRouteStatusNotStarted(route.getId());
    }

    /**
     * 重新申请
     *
     * @param id
     * @return
     */
    public int repeatApply(Integer id) {
        AsseTransCheck transCheck = transCheckRepository.getOne(id);
        transCheck.setStatus(1);
        transCheckRepository.save(transCheck);

        AsseTransSheet trans = transSheetRepository.getOne(transCheck.getTransId());
        AsseAssemblyRoute route = assemblyRouteRepository.getOne(trans.getRouteId());
        AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(route.getSheetId());
        logService.saveLog("派工单-重新申请质检", "转序单ID：" + trans.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName() + "<br>工序：" + route.getRoute()
                + "<br>申请数量：" + trans.getNum());
        return 1;
    }

    /**
     * @Author wsg
     * @Date 10:52 2021/5/13
     * @Description 获取接收的生产令列表
     **/
    public List<Select2Model> getRecProdNoList(String prodNo) {
        return applyMapper.getRecProdNoList(prodNo);
    }

    /**
     * @Author wsg
     * @Date 10:52 2021/5/13
     * @Description 获取接收的类型列表
     **/
    public List<Select2Model> getRecProdNoSpecialList(String prodNo) {
        return applyMapper.getRecProdNoSpecialList(prodNo);
    }

    /**
     * @Author wsg
     * @Date 10:52 2021/5/13
     * @Description 获取接收的部分列表
     **/
    public List<Select2Model> getRecProdNoPartList(String prodNo, String special) {
        return applyMapper.getRecProdNoPartList(prodNo, special);
    }

    /**
     * @Author wsg
     * @Date 11:10 2021/5/13
     * @Description 获取接收的图号列表
     **/
    public List<Select2Model> getRecProdNoDrawNoList(String prodNo, String special, Integer partId) {
        return applyMapper.getRecProdNoDrawNoList(prodNo,special,partId);
    }

}
